package com.sunday.aomi.ui.product;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sunday.common.adapter.CommonAdapter;
import com.sunday.common.adapter.RecylerViewHolder;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.StringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.banner.ConvenientBanner;
import com.sunday.common.widgets.banner.holder.ViewHolderCreator;
import com.sunday.common.widgets.taosty.Toasty;
import com.sunday.aomi.R;
import com.sunday.aomi.adapter.ProductDetailRecAdapter;
import com.sunday.aomi.adapter.StringBannerHolder;
import com.sunday.aomi.http.ApiClient;
import com.sunday.aomi.ui.order.CartActivity;
import com.sunday.aomi.ui.widgets.PopBuyWindow;
import com.sunday.aomi.widgets.DividerGridItemDecoration;
import com.sunday.aomi.widgets.ShareWindow;
import com.sunday.member.constv.ConstValue;
import com.sunday.member.entity.Member;
import com.sunday.member.entity.RollImage;
import com.sunday.member.entity.product.Product;
import com.sunday.member.entity.product.ProductDetail;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;
import com.umeng.socialize.UMShareAPI;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;



/**
 * Created by 刘涛 on 2017/5/24.
 */

public class ProductDetailActivity extends BaseActivity {


    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.left_txt)
    TextView leftTxt;
    @Bind(R.id.right_menu)
    ImageView rightMenu;
    @Bind(R.id.right_txt)
    TextView rightTxt;
    @Bind(R.id.left_menu)
    ImageView leftMenu;
    @Bind(R.id.total_layout)
    RelativeLayout totalLayout;
    @Bind(R.id.banner)
    ConvenientBanner banner;
    @Bind(R.id.product_title)
    TextView productTitle;
    @Bind(R.id.btn_share)
    ImageView btnShare;
    @Bind(R.id.product_price)
    TextView productPrice;
    @Bind(R.id.product_old_price)
    TextView productOldPrice;
    @Bind(R.id.btn_collect)
    ImageView btnCollect;
    @Bind(R.id.nested_scroll_webview1)
    WebView webView;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.img_cart)
    ImageView imgCart;
    @Bind(R.id.add_cart)
    TextView addCart;
    @Bind(R.id.buy_now)
    TextView buyNow;
    @Bind(R.id.bottom_layout)
    LinearLayout bottomLayout;

    private long productId;
    private ProductDetail productDetail;
    private int isCollection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_detail);
        ButterKnife.bind(this);
        productId = getIntent().getLongExtra("productId", 0);
        initView();
        getProductDetail();
    }

    private void initView() {
        title.setText("产品");
        /*rightMenu.setVisibility(View.VISIBLE);
        rightMenu.setImageResource(R.mipmap.share_black);*/

    }

    private void getProductDetail() {
        String nonce = MD5Utils.random();//随机数
        String[] str1 = new String[]{"productId", "nonce"};
        String[] str2 = new String[]{String.valueOf(productId), nonce};
        showLoadingDialog(0);
        Call<ResultDO<ProductDetail>> call = MemberClient.getApiAdapter().getProductDetail(productId, null, nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<ProductDetail>>() {
            @Override
            public void onResponse(Call<ResultDO<ProductDetail>> call, Response<ResultDO<ProductDetail>> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    productDetail = response.body().getResult();
                    updateView();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<ProductDetail>> call, Throwable t) {
                dissMissDialog();
            }
        });
    }

    private void updateView() {
        List<String> bannerImgs = new ArrayList<>();
        if (productDetail.getRollImages() != null && !productDetail.getRollImages().isEmpty()) {
            for (RollImage item : productDetail.getRollImages()) {
                if (!TextUtils.isEmpty(item.getUrl())) {
                    bannerImgs.add(item.getUrl());
                }
            }
        }
        banner.startTurning(3000);
        banner.setPages(new ViewHolderCreator<StringBannerHolder>() {
            @Override
            public StringBannerHolder createHolder() {
                return new StringBannerHolder();
            }
        }, bannerImgs)
                .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused});
        banner.notifyDataSetChanged();
        productTitle.setText(productDetail.getName());
        productPrice.setText(String.format("￥%s", productDetail.getPrice().setScale(2, RoundingMode.HALF_UP)));
        productOldPrice.setText(String.format("￥%s", productDetail.getMarketPrice().setScale(2, RoundingMode.HALF_UP)));
        productOldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);


        //启用支持javascript
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setBuiltInZoomControls(false);
        settings.setSupportZoom(false);
        settings.setDomStorageEnabled(true);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!TextUtils.isEmpty(url)) {
                    view.loadUrl(url);
                } else {
                    dissMissDialog();
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                dissMissDialog();
            }
        });
        webView.loadUrl(MemberClient.PRODUCT_DETAIL_URL + String.valueOf(productId));

        if (productDetail.getProducts() != null && !productDetail.getProducts().isEmpty()) {
            ProductDetailRecAdapter adapter = new ProductDetailRecAdapter(mContext, productDetail.getProducts());
            GridLayoutManager layoutManager = new GridLayoutManager(mContext, 2);
            layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    if (position == 0) {
                        return 2;
                    } else {
                        return 1;
                    }
                }
            });

            recyclerView.setLayoutManager(layoutManager);
            recyclerView.addItemDecoration(new DividerGridItemDecoration(5));
            recyclerView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }

        //收藏
        btnCollect.setImageResource(productDetail.getIsCollection()==0?R.mipmap.collect_normal:R.mipmap.collect_pressed);
        isCollection=productDetail.getIsCollection();
    }

    private PopBuyWindow popBuyWindow;
    private String shareUrl="http://mobile.51huaguoshan.com/sunday/mobile/apk/download?type=1";//暂时替代
    @OnClick({R.id.btn_collect, R.id.btn_share, R.id.img_cart, R.id.add_cart, R.id.buy_now})
    void onClick(View v) {
        if (productDetail==null){return;}
        switch (v.getId()) {
            case R.id.img_cart:
                intent=new Intent(mContext, CartActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_collect:
                doCollection();
                break;
            case R.id.btn_share:
                if(productDetail.getShareUrl()==null||productDetail.getShareTitle()==null){
                    ToastUtils.showToast(mContext,"数据不完整");
                    return;
                }
                ShareWindow shareWindow=new ShareWindow(mContext,productDetail.getShareUrl(),productDetail.getName(),productDetail.getImage(),productDetail.getShareDesc());
                shareWindow.showPopupWindow(btnShare);
                break;
            case R.id.add_cart:
                if (popBuyWindow==null){
                    popBuyWindow=new PopBuyWindow(mContext, ConstValue.TYPE_ADDCART,
                            productDetail.getImage(),productDetail.getId(),String.format("%s",productDetail.getPrice().setScale(2,RoundingMode.HALF_UP)),
                            productDetail.getSaleNumber());
                }else {
                    popBuyWindow.setBuyType(ConstValue.TYPE_ADDCART);
                }
                popBuyWindow.showPopupWindow(addCart);
                break;
            case R.id.buy_now:
                if (popBuyWindow==null){
                    popBuyWindow=new PopBuyWindow(mContext, ConstValue.TYPE_BUY_NOW,productDetail.getImage(),productDetail.getId(),String.format("%s",productDetail.getPrice().setScale(2,RoundingMode.HALF_UP)),
                            productDetail.getSaleNumber());
                }else {
                    popBuyWindow.setBuyType(ConstValue.TYPE_BUY_NOW);
                }
                popBuyWindow.showPopupWindow(buyNow);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode,resultCode,data);
    }

    private void doCollection(){
        String nonce=MD5Utils.random();
        String otherId= String.valueOf(productId);
        String[] str1=new String[]{"type","otherId","nonce"};
        String[] str2=new String[]{"1",String.valueOf(otherId),nonce};
        showLoadingDialog(0);
        Call<ResultDO> call= MemberClient.getApiAdapter().doCollection("1",otherId,nonce,SignUtil.getSign(str1,str2));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish||response.body()==null){return;}
                dissMissDialog();
                if (response.body().getCode()==0){
                    ToastUtils.showToast(mContext,isCollection==0?"已收藏":"已取消收藏");
                    isCollection=isCollection==0?1:0;
                    btnCollect.setImageResource(isCollection==0?R.mipmap.collect_normal:R.mipmap.collect_pressed);
                }else {
                    ToastUtils.showToast(mContext,response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext,R.string.network_error);
            }
        });
    }



}
